
package member
import (
	"strings"
	"errors"
	"time"
	"dhfshop/models"
	"dhfshop/models/consts"
	"github.com/astaxie/beego/orm"
)
// 商家创建的充值活动
type BalanceActivity struct {
	BalanceActivityId int64     `orm:"column(balance_activity_id);pk;auto" json:"balance_activity_id" form:"balance_activity_id"`  //活动id
    PartnerId         int64       `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"`                  //组织id
	StoreId           int64       `orm:"column(store_id);index" json:"store_id" form:"store_id"`                        //门店id
	MemberId          int64       `orm:"column(member_id)" json:"member_id" form:"member_id"`                           //操作者id
	Name              string    `orm:"column(name);size(32);null" json:"name" form:"name"`                            //活动名称
	StartTime         time.Time `orm:"column(start_time);type(datetime);null" json:"-" form:"-"`                      //活动开始时间
	StartTimeStr      string    `orm:"-" json:"start_time" form:"start_time"`                                         //输入输出
	EndTime           time.Time `orm:"column(end_time);type(datetime);null" json:"-" form:"-"`                        //活动结束时间
	EndTimeStr        string    `orm:"-" json:"end_time" form:"end_time"`                                             //输入输出
	Money             float32   `orm:"column(money);digits(12);decimals(2)" json:"money" form:"money"`                //充多少元
    MoneyGift         float32   `orm:"column(money_gift);digits(12);decimals(2)" json:"money_gift" form:"money_gift"` //送多少元
	CreatedAt         time.Time `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"` 
	CreatedAtStr      string    `orm:"-" json:"created_at,omitempty" form:"-"`
    UpdatedAt         time.Time `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"`         
	UpdatedAtStr      string    `orm:"-" json:"updated_at,omitempty" form:"-"`
}

func init() {
    orm.RegisterModel(new(BalanceActivity))   
}


func AddBalanceActivity(m *BalanceActivity) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetBalanceActivityById(id int64) (v *BalanceActivity, err error) {
	o := models.GetDefaultDB()
	v = &BalanceActivity{BalanceActivityId: id}
	if err = o.Read(v); err == nil {
		v.StartTimeStr = v.StartTime.Format(consts.DATETIME_FORMAT)
		v.EndTimeStr = v.EndTime.Format(consts.DATETIME_FORMAT)
		v.CreatedAtStr = v.CreatedAt.Format(consts.DATETIME_FORMAT)
		v.UpdatedAtStr = v.UpdatedAt.Format(consts.DATETIME_FORMAT)
		return v, nil
	}
	return nil, err
}

func GetBalanceActivity(query map[string]string)(ad *BalanceActivity,err error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(BalanceActivity))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)	
	}
	if err = qs.One(ad); err == nil {
		return ad, nil
	}
	return nil, err
}

func GetAllBalanceActivitys(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*BalanceActivity,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(BalanceActivity))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*BalanceActivity
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, temp := range lists {
			temp.StartTimeStr = temp.StartTime.Format(consts.DATETIME_FORMAT)
			temp.EndTimeStr = temp.EndTime.Format(consts.DATETIME_FORMAT)
			temp.CreatedAtStr = temp.CreatedAt.Format(consts.DATETIME_FORMAT)
		    temp.UpdatedAtStr = temp.UpdatedAt.Format(consts.DATETIME_FORMAT)
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateBalanceActivityById(m *BalanceActivity, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := BalanceActivity{BalanceActivityId: m.BalanceActivityId}
	if err = o.Read(&v); err == nil {
		if _, err = o.Update(m, k...); err != nil {
			return err
		}
	}
	return
}

func DeleteBalanceActivity(id int64) (err error) {
	o := models.GetDefaultDB()
	v := BalanceActivity{BalanceActivityId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return
		}
	}
	return
}

func CheckChargeActivityValid(partnerId int64,curTime time.Time,amount float32) bool {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(BalanceActivity)).Filter("partner_id",partnerId).Filter("money",amount)
	valid := qs.Filter("start_time__lt",curTime).Filter("end_time__gt",curTime).Exist()
	return valid
}

